import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { ElMessage } from 'element-plus';

import LoginView from '@/views/auth/LoginView.vue';
import RegisterView from '@/views/auth/RegisterView.vue';

import BackstageLayout from '@/components/layout/BackstageLayout.vue';
import FrontstageLayout from '@/components/layout/FrontstageLayout.vue';

import FrontFrame from '@/views/front/FrontView.vue';
import AnnounceView from '@/views/front/AnnounceView.vue';
import PersonalView from '@/views/front/PersonalView.vue';
import CourseView from '@/views/course/CourseView.vue';
import CourseManage from '@/views/course/CourseManage.vue';
import CourseJoinManage from '@/views/course/CourseJoinManage.vue';
import QuestionManage from '@/views/exam/QuestionManage.vue';
import PaperManage from '@/views/exam/PaperManage.vue';
import ExamTake from '@/views/exam/ExamTake.vue';
import ExamView from '@/views/exam/ExamView.vue';
import ExamGrade from '@/views/exam/ExamGrade.vue';
import GradePage from '@/views/exam/GradePage.vue';
import ResourceManage from '@/views/resource/ResourceManage.vue';
import ResourceView from '@/views/resource/ResourceView.vue';
import ResourceDetail from '@/views/resource/ResourceDetail.vue';
import MessageManage from '@/views/message/MessageManage.vue';
import MessageView from '@/views/message/MessageView.vue';
import CheckInView from '@/views/checkin/CheckInView.vue';
import CheckInManage from '@/views/checkin/CheckInManage.vue';

const routes: Array<RouteRecordRaw> = [
  { path: '/', redirect: '/login' },
  { path: '/login', name: 'LoginView', component: LoginView },
  { path: '/register', name: 'RegisterView', component: RegisterView },
  {
    path: '/front',
    component: FrontstageLayout,
    children: [
      { path: 'view', name: 'FrontFrame', component: FrontFrame },
      { path: 'announcement', name: 'AnnounceView', component: AnnounceView },
      { path: 'personal', name: 'PersonalView', component: PersonalView },
      { path: 'course', name: 'CourseView', component: CourseView },
      { path: 'exam', name: 'ExamTake', component: ExamView }, // 学生考试列表
      { path: 'exam/:paperId', name: 'ExamPage', component: ExamTake }, // 考试页面
      { path: 'resource', name: 'ResourceView', component: ResourceView },
      { path: 'resource/:id', name: 'ResourceDetail', component: ResourceDetail },
      { path: 'message', name: 'MessageView', component: MessageView },
      { path: 'check-in', name: 'CheckInView', component: CheckInView }
    ],
  },
  {
    path: '/course',
    component: BackstageLayout,
    children: [
      { path: 'manage', name: 'CourseManage', component: CourseManage },
      { path: 'join-manage', name: 'CourseJoinManage', component: CourseJoinManage },
    ],
  },
  {
    path: '/exam',
    component: BackstageLayout,
    children: [
      { path: 'question', name: 'QuestionManage', component: QuestionManage },
      { path: 'paper', name: 'PaperManage', component: PaperManage },
      { path: 'grade', name: 'ExamGrade', component: ExamGrade }, // 试卷评分列表
      { path: 'grade/:submissionId', name: 'GradePage', component: GradePage }, // 评分页面
    ],
  },
  {
    path: '/resource',
    component: BackstageLayout,
    children: [
      { path: 'manage', name: 'ResourceManage', component: ResourceManage },
    ],
  },
  {
    path: '/message',
    component: BackstageLayout,
    children: [
      { path: 'manage', name: 'MessageManage', component: MessageManage },
    ],
  },
  {
    path: '/check-in',
    component: BackstageLayout,
    children: [
      { path: 'manage', name: 'CheckInManage', component: CheckInManage },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach(async (to, from, next) => {
  const { useUserStore } = await import('../stores/api/user');
  const { usePathPermissionStore } = await import('@/stores/project/path-permission');

  const userStore = useUserStore();
  const permissionStore = usePathPermissionStore();

  const userRole = userStore.user?.role;
  const restrictedPaths = permissionStore.getForbiddenPaths(userRole || '');

  // 用户不存在则重定向到登录
  if (!userRole && !permissionStore.publicPaths.includes(to.path)) {
    logRoute(to, userStore, permissionStore, '未登录，重定向到登录页');
    next('/login');
    return;
  }

  if (!restrictedPaths) {
    logRoute(to, userStore, permissionStore, '权限信息丢失');
    ElMessage.error('权限信息丢失，请刷新网页');
    next(false);
    return;
  }

  // 检查路径是否在受限路径中
  if (restrictedPaths.some((path: string) => to.path.startsWith(path))) {
    logRoute(to, userStore, permissionStore, '权限不足');
    ElMessage.error('权限不足，无法访问该页面');
    next(false);
    return;
  }

  next();
});

// 定义路由守卫日志记录函数
function logRoute(to, userStore, permissionStore, reason) {
  const userRole = userStore.user?.role;
  console.log('路由守卫拦截:', {
    to: to.path,
    reason,
    user: userStore.user,
    restrictedPaths: permissionStore.getForbiddenPaths(userRole || ''),
  });
}

export default router;